package com.huangjian.controller;


import com.huangjian.pojo.Product;
import com.huangjian.service.ProductServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//提供Restfull服务!!
@RestController
public class ProductController {

    @Autowired
    private ProductServiceImpl productService;

    @PostMapping("/product/add")
    public boolean addProduct(Product product) {
        return productService.addProduct(product);
    }


    @GetMapping("/product/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGetProduct") //失败了就会调用下面的这个备选方案
    public Product getProduct(@PathVariable("id") Integer id) {
        Product product = productService.queryById(id);
        if (product == null) {
            throw new RuntimeException("不存在该商品，或者信息无法找到");
        }
        return product;
    }

    @GetMapping("/product/list")
    public List<Product> queryAll() {
        return productService.queryAll();
    }

    //备选方案
    public Product hystrixGetProduct(@PathVariable("id") Integer id) {
        return new Product()
                .setPid(id)
                .setPname("商品不存在")
                .setPprice(0)
                .setPcategory("所属类别不存在");
    }
}
